package com.easylinkin.linkappapi.premeeting.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.premeeting.entity.RailPreMeeting;
import com.easylinkin.linkappapi.premeeting.service.RailPreMeetingService;

import com.easylinkin.linkappapi.premeeting.vo.RailPreMeetingQueryVo;
import com.easylinkin.linkappapi.premeeting.vo.RailPreMeetingVo;
import com.easylinkin.linkappapi.premeeting.vo.RailPreMeetingCalendarVo;
import com.easylinkin.linkappapi.premeeting.vo.RailPreMeetingCalendarQueryVo;
import com.easylinkin.linkappapi.premeeting.vo.RailPreMeetingGridSwitchVo;

import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogModule;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import cn.hutool.core.codec.Base64;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import org.springframework.core.io.ClassPathResource;
import java.util.Map;

/**
 * @author: zl
 * @Date: 2025-06-30
 * @Description: 班前会管理
 */
@RestController
@RequestMapping("railPreMeeting")
@Api(tags = "班前会管理")
public class RailPreMeetingController {
  
  @Autowired
  private RailPreMeetingService railPreMeetingService;

  /**
   * @Description: 增加班前会
   * @author zl
   * @date 2025-06-30
   */
  @PostMapping
  @ApiOperation("增加班前会")
  public RestMessage insert(@RequestBody RailPreMeeting railPreMeeting){
    railPreMeetingService.insert(railPreMeeting);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 删除班前会（包含批量删除）
   * @author zl
   * @date 2025-06-30
   */
  @DeleteMapping
  @ApiOperation("删除班前会（包含批量删除）")
  @CommonOperateLogAnnotate(module = LogModule.SAFE_MANAGEMENT, desc = "")
  public RestMessage delBatch(@RequestBody RailPreMeetingVo railPreMeetingVo){
    Assert.notEmpty(railPreMeetingVo.getIds(),"id不能为空");
    railPreMeetingService.delBatch(railPreMeetingVo.getIds().stream().map(Long::valueOf).collect(java.util.stream.Collectors.toList()));
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 编辑班前会
   * @author zl
   * @date 2025-06-30
   */
  @PutMapping
  @ApiOperation("编辑班前会")
  @CommonOperateLogAnnotate(module = LogModule.SAFE_MANAGEMENT, desc = "")
  public RestMessage updateById(@RequestBody RailPreMeeting railPreMeeting){
    Assert.notNull(railPreMeeting.getId(),"id不能为空");
    railPreMeetingService.updateOne(railPreMeeting);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 根据id查询班前会详情
   * @author zl
   * @date 2025-06-30
   */
  @GetMapping("{id}")
  @ApiOperation("根据id查询班前会详情")
  public RestMessage findById(@PathVariable("id")String id) {
    Assert.notNull(id,"id不能为空");
    RailPreMeetingVo railPreMeetingVo = railPreMeetingService.findById(id);
    return RestBuilders.successBuilder().data(railPreMeetingVo).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询
   * @author zl
   * @date 2025-06-30
   */
  @PostMapping("list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryListByPage(@RequestBody RequestModel<RailPreMeetingQueryVo> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<RailPreMeetingVo> record = railPreMeetingService.queryListByPage(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 获取班前会日历数据
   * @author kyf
   * @date 2025-06-30
   */
  @GetMapping("calendar")
  @ApiOperation("获取班前会日历数据")
  public RestMessage getCalendarData(@RequestParam("yearMonth") String yearMonth){
    Assert.hasText(yearMonth, "年月参数不能为空");
    Assert.isTrue(yearMonth.matches("\\d{4}-\\d{2}"), "年月格式错误，应为：2025-01");

    RailPreMeetingCalendarQueryVo queryVo = new RailPreMeetingCalendarQueryVo();
    queryVo.setYearMonth(yearMonth);

    List<RailPreMeetingCalendarVo> calendarData = railPreMeetingService.getCalendarData(queryVo);
    return RestBuilders.successBuilder().data(calendarData).build();
  }

  /**
   * @Description: 获取网格点切换数据（显示所有网格点及其数据状态）
   * @author kyf
   * @date 2025-06-30
   */
  @GetMapping("gridSwitch")
  @ApiOperation("获取网格点切换数据")
  public RestMessage getGridSwitchData(@RequestParam("startTime") String startTime,
                                       @RequestParam("endTime") String endTime){
    Assert.hasText(startTime, "开始时间不能为空");
    Assert.hasText(endTime, "结束时间不能为空");

    try {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date start = sdf.parse(startTime);
      Date end = sdf.parse(endTime);

      List<RailPreMeetingGridSwitchVo> gridSwitchData = railPreMeetingService.getGridSwitchData(start, end);
      return RestBuilders.successBuilder().data(gridSwitchData).build();
    } catch (Exception e) {
      throw new BusinessException("时间格式错误，应为：yyyy-MM-dd HH:mm:ss");
    }
  }

  /**
   * @Description: 班前会按年月导出
   * @author kyf
   * @date 2025-06-30
   */
  @GetMapping("export")
  @ApiOperation("班前会按年月导出")
  public void exportByYearMonth(@RequestHeader("User-Agent") String header,
                                @RequestParam("yearMonth") String yearMonth,
                                HttpServletResponse response) throws IOException {
    Assert.hasText(yearMonth, "年月参数不能为空");
    Assert.isTrue(yearMonth.matches("\\d{4}-\\d{2}"), "年月格式错误，应为：2025-01");

    // 获取导出数据
    Map<String, Object> dataMap = railPreMeetingService.getExportDataByYearMonth(yearMonth);

    // 生成Excel文件
    String tempName = "railPreMeeting.xlsx";
    TemplateExportParams params = new TemplateExportParams(
        new ClassPathResource("templates/" + tempName).getPath(), true);
    params.setColForEach(true);
    Workbook workbook = ExcelExportUtil.exportExcel(params, dataMap);

    // 生成文件名：xx项目x年x月班前会台账
    String projectName = (String) dataMap.get("projectName");
    String timeStr = (String) dataMap.get("timeStr");
    String filename;
    String s = projectName + timeStr + "班前会台账";
    if(header.contains("Firefox")){
      //说明是火狐浏览器,使用Base64Encoder类进行编码
      filename = "=?utf-8?B?" + Base64.encode(s.getBytes("utf-8")) + "?=";
    }else{
      //是其他浏览器,使用URLEncoder类进行编码
      filename = String.valueOf(URLEncoder.encode(s, "UTF-8"));
    }
    // 指定下载的文件名--设置响应头
    response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");
    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    // 写出数据输出流到页面
    OutputStream output = response.getOutputStream();
    BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
    workbook.write(bufferedOutPut);
    bufferedOutPut.flush();
    bufferedOutPut.close();
    output.close();
  }
}
